package com.yungam.influxdb.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Service
public class CollectInfluxService {

    @Resource
    private InfluxdbCommonService commonService;

    public List<Map<String, Object>> getCollectData(String ip, Long[] range, Integer interval) {
        List<Map<String, Object>> ans = Lists.newArrayList();

        List<FluxTable> tables = commonService.queryByIp(ip, range, interval);

        for (FluxTable table : tables) {
            List<FluxRecord> records = table.getRecords();
            for (FluxRecord fluxRecord : records) {
                Map<String, Object> cur = Maps.newHashMap();
                // createTime
                Instant instant = (Instant) fluxRecord.getValues().get("_time");
                Long creatTime = new Date(instant.toEpochMilli()).getTime();
                // itemValue
                Object itemValue = fluxRecord.getValues().get("_value");
                if (Objects.isNull(itemValue)) itemValue = 0d;
                else {
                    Double d = (Double) itemValue;
                    String format = String.format("%.2f", d);
                    itemValue = Double.parseDouble(format);
                }
                // itemNo
                Object itemNo = fluxRecord.getValues().get("id");
                // itemName
                Object itemName = fluxRecord.getValues().get("name");
                cur.put("itemNo", itemNo);
                cur.put("itemName", itemName);
                cur.put("itemValue", itemValue);
                cur.put("createTime", creatTime);
                ans.add(cur);
            }
        }

        return ans;
    }

}

